package com.fateai.module.swipeItemHelper;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.chad.library.adapter4.BaseQuickAdapter;
import com.fateai.module.R;

import java.util.ArrayList;
import java.util.List;

public class MyAdapter extends BaseQuickAdapter<UserData,MyAdapter.MyViewHolder> {

    public MyAdapter() {
    }

    public MyAdapter(@NonNull List<? extends UserData> items) {
        super(items);
    }

    // 定义菜单事件监听器接口
    public interface OnMenuItemClickListener {
        void onMenuItemClick(int position, int menuItemId);
    }

    private OnMenuItemClickListener menuItemClickListener;

    public void setOnMenuItemClickListener(OnMenuItemClickListener listener) {
        this.menuItemClickListener = listener;
    }

    @Override
    protected void onBindViewHolder(@NonNull MyViewHolder myViewHolder, int position, @Nullable UserData userData) {
        // 绑定数据...

        // 获取菜单视图
        View menuView = myViewHolder.getMenuView();
        TextView textView = myViewHolder.contentView.findViewById(R.id.content_name);
        textView.setText(userData.name +" "+userData.age+" "+userData.email);

        // 绑定菜单中的所有按钮
        bindMenuItems(menuView, position);
    }

    @NonNull
    @Override
    protected MyViewHolder onCreateViewHolder(@NonNull Context context, @NonNull ViewGroup viewGroup, int i) {
        // 加载布局文件
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_layout, viewGroup, false);
        // 返回自定义的ViewHolder
        return new MyViewHolder(view);
    }

    private void bindMenuItems(View menuView, int position) {
        // 遍历菜单中的所有可点击视图
        List<View> clickableViews = findAllClickableViews(menuView);

        for (View view : clickableViews) {
            view.setOnClickListener(v -> {
                if (menuItemClickListener != null) {
                    // 传递位置和视图ID作为标识
                    menuItemClickListener.onMenuItemClick(position, v.getId());
                }
            });
        }
    }

    // 递归查找所有可点击的视图
    private List<View> findAllClickableViews(View view) {
        List<View> result = new ArrayList<>();

        if (view.isClickable()) {
            result.add(view);
        }

        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            for (int i = 0; i < viewGroup.getChildCount(); i++) {
                View child = viewGroup.getChildAt(i);
                result.addAll(findAllClickableViews(child));
            }
        }

        return result;
    }


    public static class MyViewHolder extends SwipeMenuHelper.SwipeViewHolder {
        public MyViewHolder(@NonNull View itemView) {
            super(itemView, R.id.content_layout, R.id.menu_layout);
        }
    }
}
